import React, {useEffect, useState} from 'react'
import {Form, Button, Input, Modal, Row, Col, Card, Select, DatePicker, InputNumber, Upload, message} from 'antd'
import {connect} from 'umi'
import EditAwardTable from './EditAwardTable'
import { PlusOutlined } from '@ant-design/icons'
import {getEmpByUnitId,getAwardInfo} from '../../service'
import moment from 'moment';
import {getUploadUrl} from "@/utils/upload";
import {UploadOutlined} from '@ant-design/icons';
import {awardTypeList} from "@/utils/constant";
import {findItemByTree} from "@/utils/functions";
import SelectUserModal from "@/pages/components/SelectUserModal";

const FormItem = Form.Item
const {TextArea} = Input;
const formLayout = {
  labelCol: {span: 7},
};

const {Option} = Select;

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const CreateForm = (props) => {

  const {onSubmit, onCancel, visible, currentUser, global = {}, reanpu, loading, record , show} = props;
  const {options = {}} = global;
  const {orgTree = []} = options;
  const [form] = Form.useForm();
  const [userList, setUserList] = useState([]);
  const [userCodeList, setUserCodeList] = useState([]);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [unitData, setUnitData] = useState([]);
  const [isDisabled,setIsDisabled] = useState(false);
  const [valve,setValve] = useState(false);
  const [delList,setDelList] = useState([]);
  const [userModalVisible, setUserModalVisible] = useState(false);

  useEffect(() => {
    if (visible && record) {
      (record.packageId !== null) ? setIsDisabled(true):setIsDisabled(false);
      if(show){
        setIsDisabled(true);
      }
      onChangeOrgId(parseInt(record.orgId));
      if(record.awardUnitname){
        handleChangeUnit(parseInt(record.awardUnitname));
      }
      let t = record.awardPersonnel ? record.awardPersonnel.split(",") : [];
      form.setFieldsValue({...record,createTime: moment(record.createTime),type:record.type,
        awardOrgId:parseInt(record.orgId),awardUnitname:record.awardUnitname ? [parseInt(record.awardUnitname)] : [],
        urlIds:record.url,awardPersonnel:t,reservedType:record.awardType !== null ? record.awardType : record.reservedType
      });
      if(record.url){
        let fileUrlList = record.url.split(',');
        setFileUploadUrls(fileUrlList);
        fileUrlList.forEach((item,index) =>{
          uploadedFiles.push({
            uid: index,
            name: item.split('----')[1],
            status: 'done',
            url: item,
          })
        });
      }
      getAwardInfo(record.serialNum).then(res => {
        setUserCodeList(res);
      });
    } else if (currentUser) {
      form.setFieldsValue({applicantName: currentUser.name, createTime: moment(), ...currentUser})
    }
  }, [visible]);

  const onFormCancel = () => {
    setIsDisabled(false);
    form.resetFields();
    setUserCodeList([]);
    onCancel();
    uploadedFiles = [];
    setValve(false);
    setFileUploadUrls([]);
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    let temp = fieldsValue.list || [];
    if(temp.length > 0){
      let isContinue = true;
      temp.forEach(item => {
        if(item.awardType === null){
          message.error("奖罚类型不能为空！");
          isContinue = false;
        }else if(item.amount === null || item.amount === 0){
          message.error("奖罚金额不能为空！");
          isContinue = false;
        }else if(item.amountOne === null || item.amountOne === 0){
          message.error("月份奖罚金额不能为空！");
          isContinue = false;
        }
      });
      if (!isContinue)
        return;
    }else{
      message.error("奖罚人员列表不能为空！");
      return;
    }
    if(valve){
      message.error("奖罚人员总金额不能超过剩余金额，请核实再提交！");
      return;
    }
    onSubmit({...fieldsValue, fileUrlList: fileUploadUrls,usercode:currentUser.usercode,id:record && record.id});
    form.resetFields();
    setUserCodeList([]);
    uploadedFiles = [];
    setValve(false);
    setFileUploadUrls([]);
  };

  const fileList = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls, res.file.response]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  const onChangeOrgId = (value) => {
    setUnitData([]);
    form.setFieldsValue({awardUnitname: [], awardPersonnel: []});
    setUserList([]);
    const item = findItemByTree(orgTree, value);
    setUnitData(item.children);
  };

  const handleChangeUnit = (value) => {
    getEmpByUnitId(value).then(res => {
      setUserList(res);
    });
  };

  const OnCheckSum = (value, key) => {
    const fieldsValue = form.getFieldsValue();
    if (key === 'distributionAmount') {
      if (value > fieldsValue.amount) {
        message.error('分配金额不能超过总金额！');
        form.setFieldsValue({distributionAmount:null});
      }
    } else if (key === 'reservedAmount') {
      if (value > fieldsValue.distributionAmount) {
        message.error('部门预留金额不能超过分配金额！');
        form.setFieldsValue({reservedAmount:null});
      }
    }else if(key === 'list'){
      let tempSum = 0;//list总金额
      value && value.map((item) => {
        let temp = parseInt(tempSum);
        tempSum =  parseInt(item.amount) + temp;
      });
      //剩余金额 = 分配金额 - 部门预留金额
      let surplus = fieldsValue.distributionAmount - fieldsValue.reservedAmount;
      if (tempSum > surplus) {
        message.error('个人分配金额不能超过剩余总金额！');
        setValve(true);
      }else{
        setValve(false);
      }
    }
  };

  const confirmSelectedUsers = (values) =>{
    let users = [];
    if (record && record.packageId){
      let errorNames = [];
       values.forEach(item => {
        if (item.orgId === record.orgId){
          if (userCodeList.filter(item2 => item2.employeeCode === item.code).length < 1){
            users.push({
              employeeCode: item.code,
              employeeName: item.name,
              orgname: item.orgname,
              orgId: item.orgId,
              unitname: item.unitname,
              unitId: item.unitId,
              oid: item.oid
            });
          }
        }else {
          errorNames.push(item.name);
        }
      });
      if (errorNames.length>0)
        message.error(`添加失败，员工${errorNames.toString()}不符合分配规则！`);
    }else {
      values.forEach(item => {
        if (userCodeList.filter(item2 => item2.employeeCode === item.code).length < 1)
          users.push({
            employeeCode: item.code,
            employeeName: item.name,
            orgname: item.orgname,
            orgId: item.orgId,
            unitname: item.unitname,
            unitId: item.unitId,
            oid: item.oid
          });
      });
    }
    setUserCodeList([...userCodeList,...users]);
    setUserModalVisible(false);
  };

  const delFunction = (code) => {
    setUserCodeList(userCodeList.filter(item => item.employeeCode !== code));
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="applicantName" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orgname" label="申请公司">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="department" label="申请部门">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="createTime" label="申请日期">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="awardName" label="奖罚名称" rules={[{required: true, message: '奖罚名称不能为空！'}]}>
              <Input disabled={isDisabled} />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="type" label="奖罚种类" rules={[{required: true, message: '奖罚种类不能为空！'}]}>
              <Select disabled={isDisabled} placeholder="请选择奖罚种类" showSearch filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }>
                {reanpu && reanpu.map((item, index) => {
                  return (
                    <Option value={`${item.code}`} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem label={<><span className='asterisk'>*</span>总金额</>}>
              <FormItem noStyle name="amount" rules={[{required: true, message: '总金额不能为空！'}, ({
                validator(rule, value) {
                  let pattern = /(^[1-9]([0-9]*)$|^[0-9]$)/;
                  if (pattern.test(value)) {
                    return Promise.resolve();
                  }
                  return Promise.reject('请输入数字类型的正确金额');
                },
              })]}>
                <InputNumber disabled={isDisabled} style={{width: '90%', marginRight: '10px'}}/>
              </FormItem>
              元
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem label={<><span className='asterisk'>*</span>分配金额</>}>
              <FormItem noStyle name="distributionAmount" rules={[{required: true, message: '分配金额不能为空！'}, ({
                validator(rule, value) {
                  let pattern = /(^[1-9]([0-9]*)$|^[0-9]$)/;
                  if (pattern.test(value)) {
                    return Promise.resolve();
                  }
                  return Promise.reject('请输入数字类型的正确金额');
                },
              })]}>
                <InputNumber onChange={(value) => OnCheckSum(value,'distributionAmount')} disabled={isDisabled} style={{width: '90%', marginRight: '10px'}}/>
              </FormItem>
              元
            </FormItem>
          </Col>
          {
            (record && record.packageId) &&
            <Col {...colStyle}>
              <FormItem name="awardOrgId" label="奖罚公司" rules={[{required: true, message: '奖罚公司不能为空！'}]}>
                <Select disabled={isDisabled} placeholder="请选择奖罚公司" allowClear>
                  {orgTree && orgTree.map((item, index) => {
                    return (
                      <Option value={item.value} key={index}>
                        {item.title}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>
          }
          <Col {...colStyle}>
            <FormItem name="reservedType" label="部门预留类型" rules={[{required: true, message: '部门预留类型不能为空！'}]}>
              <Select disabled={isDisabled} placeholder="请选择部门预留类型">
                {awardTypeList.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem label={<><span className='asterisk'>*</span>部门预留金额</>}>
              <FormItem noStyle name="reservedAmount" rules={[{required: true, message: '部门预留金额不能为空！'}, ({
                validator(rule, value) {
                  let pattern = /(^[1-9]([0-9]*)$|^[0-9]$)/;
                  if (pattern.test(value)) {
                    return Promise.resolve();
                  }
                  return Promise.reject('请输入数字类型的正确金额');
                },
              })]}>
                <InputNumber onChange={(value) => OnCheckSum(value,'reservedAmount')} disabled={show} style={{width: '90%', marginRight: '10px'}}/>
              </FormItem>
              元
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem label="奖罚附件" rules={[{required: true, message: '奖罚附件不能为空！'}]}>
              <Upload {...fileList} disabled={isDisabled}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Card title="添加奖罚人员" bordered={false} className='widthStyle' style={{marginBottom: 24}}>
            <FormItem name="list" style={{marginBottom: 5}}>
              <EditAwardTable userCodeList={userCodeList} onChange={(value) => OnCheckSum(value,'list')} show={show} delFunction={delFunction}/>
            </FormItem>
            <Button className='widthStyle' type="dashed" onClick={()=>setUserModalVisible(true)}>
              <PlusOutlined/>
              新增成员
            </Button>
          </Card>
          <Col span={24}>
            <FormItem name="remark" labelCol={{span: 2}} label="奖罚说明" rules={[{required: true, message: '请输入奖罚说明！'}]}>
              <TextArea disabled={show} rows={8} className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    if(show){
      return (
        <>
          <div style={{textAlign:'center'}}>
            <Button onClick={() => onFormCancel()}>关闭</Button>
          </div>
        </>
      )
    } else{
      return (
        <>
          <Button onClick={() => onFormCancel()}>取消</Button>
          <Button type="primary" loading={loading} onClick={() => handleSubmit()}>确认</Button>
        </>
      )
    }
  };

  return (
    <Modal
      width={'90%'}
      destroyOnClose
      title="奖罚明细分配"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{paddingTop: '24px'}}
      >
        {renderContent()}
      </Form>
      <SelectUserModal
        selectType={1}
        visible={userModalVisible}
        handleOk={confirmSelectedUsers}
        handleCancel={()=>setUserModalVisible(false)}
      />
    </Modal>
  )
};


export default connect(({user, personnel, global}) => ({
  personnel,
  currentUser: user.currentUser,
  global
}))(CreateForm)
